<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Application\Entity\UserFacebook;
use Application\Entity\User;
use Zend\Mvc\Controller\Plugin\Redirect;
use Zend\Authentication\AuthenticationService;
use Zend\Log\Logger;
use Zend\Log\Writer\Stream;
use Zend\View\Model\JsonModel;
use Application\Component\UserComponent;
use Application\Component\UserFacebookComponent;
use DateTime;

class HomeController extends AbstractActionController
{

    protected $em;

    protected $storage;

    protected $authservice;

    protected $userComponent;

    protected $userFacebookComponent;

    public function init()
    {
        if (null === $this->em) {
            $this->em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
            $this->userComponent = new UserComponent($this->em);
            $this->userFacebookComponent = new UserFacebookComponent($this->em);
        }
        return $this->em;
    }

    public function getSessionStorage()
    {
        if (! $this->storage) {
            $this->storage = $this->getServiceLocator()->get('Application\Model\MyAuthStorage');
        }
        
        return $this->storage;
    }

    public function getAuthService()
    {
        if (! $this->authservice) {
            $this->authservice = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
        }
        return $this->authservice;
    }

    public function isAuthenticate()
    {
    	
        if ($user = $this->identity()) {
        	return true;
        } else {
        	return false;
        }
    }

    public function indexAction()
    {
      
        if ($this->isAuthenticate()) {
            return $this->redirect()->toRoute('queue');
        }
        return new ViewModel();
    }

	

    public function testAction()
    {
        return new ViewModel();
    }

    public function feedAction()
    {
		$feeds = array();
		for($i=1; $i<=10; $i++)
		$feeds[] = array(
			"id"=>$i,
			"name"=> "National Geographic Channel Channel Channel Channel",
            "image"=> "http://10.0.2.2/putmark/public/test_android/cosmos.jpg",
            "status"=> "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
            "profilePic"=> "http://10.0.2.2/putmark/public/test_android/nat.jpg",
            "timeStamp"=> "1403375851930",
            "url"=> null);
        return new JsonModel(array("feed"=>$feeds));
    }

    public function albumsAction()
    {
		$feeds = array();
		for($i=1; $i<=10; $i++)
		$feeds[] = array(
			"id"=>$i,
			"name"=> "My album long title ".$i,
            "image"=> "http://10.0.2.2/putmark/public/test_android/nat.jpg",
            "nbPicts"=> 2*$i-2,
            "desc"=> "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
            "timeStamp"=> "1403375851930",
            );
        return new JsonModel(array("albums"=>$feeds));
    }

	//Photos of an album given by it's id
    public function photosAction()
    {
		$feeds = array();
		for($i=1; $i<=10; $i++)
		$feeds[] = array(
			"id"=>$i,
			"name"=> "My album long title ".$i,
            "image0"=> "http://10.0.2.2/putmark/public/test_android/nat.jpg",
            "image"=> "http://10.0.2.2/putmark/public/test_android/picts/".$i.".png",
            "nb_marks"=> 2*$i-2,
            "desc"=> "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
            "timestamp"=> "1403375851930",
            );
        return new JsonModel(array("photos"=>$feeds));
    }
	
	public function getuserAction()
    {
		$user = $this->identity();
		if($user!=null){
		    $message = $user->getJson();
		    $message["success"] = 'User connected';
			/*$message = array(
				'success' => 'User connected',
				'uid'=>$user->uid,
				'firstname'=>$user->firstname,
				'lastname'=>$user->lastname,
				//'photo'=>$user->picwithlogo==null?"http://10.0.2.2/putmark/public/test_android/user.png":$user->picwithlogo,
				'photo'=>$user->picwithlogo==null?"user.png":$user->picwithlogo,
			);*/
		}else{
			$message = array(
				'error' => 'Please log in',
			);
		}
        return new JsonModel($message);
	}
	
	//New
	public function registerAction()
    {//TODO Utiliser plutot user/validate (à renommer)
		if($this->request->isPost()){
			try{
				$row = $this->getServiceLocator()->get("UserComponent")->get($user->uid);
				$form = $this->request->getPost();
				if($row!=null){
					if(isset($form["image"])) $row->pictwithlogo = $form["image"];
					if(isset($form["firstname"])) $row->firstname = $form["firstname"];
					if(isset($form["lastname"])) $row->lastname = $form["lastname"];
					if(isset($form["middlename"])) $row->middlename = $form["middlename"];
					if(isset($form["occupation"])) $row->occupation = $form["occupation"];
					if(isset($form["aboutme"])) $row->aboutme = $form["aboutme"];
					if(isset($form["sex"])) $row->sex = $form["sex"];
					if(isset($form["username"])) $row->username = $form["username"];
					$this->getServiceLocator()->get("UserComponent")->update($row);
					$result["code"]="success";
				}else{
					$result["code"]="not connected";
				}
			}catch(\Exception $e){
				$result["code"]="error";
				$result["error"]=$e->getMessage();
			}
		}
	}
	//New
	public function validateAction()
    {
		if($this->request->isPost()){
			try{
				$form = $this->request->getPost();
				$email = $this->request->getPost("email", "");
				$code = $this->request->getPost("code", "");
				$rows = $this->getServiceLocator()->get("UserComponent")->getByEmailKeyConfirm($email, code);
				if($rows!=null && count($rows)>0){
					$row = $rows[0];
					$row->confirm = 1;
					$row->confirm_at = new DateTime("now");
					$this->getServiceLocator()->get("UserComponent")->update($row);
					$result["code"]="success";
				}else{
					$result["code"]="not connected";
				}
			}catch(\Exception $e){
				$result["code"]="error";
				$result["error"]=$e->getMessage();
			}
		}
	}
	
	//New
	public function editaccountAction()
    {
		$user = $this->identity();
		$result = array();
		if($user!=null){
			if($this->request->isPost()){
				try{
					$row = $this->getServiceLocator()->get("UserComponent")->get($user->uid);
					$form = $this->request->getPost();
					if($row!=null){
						//if(isset($form["image"]) && trim($form["image"])!="" &&$form["image"]!="-1") $row->pictwithlogo = $form["image"];
						if(isset($form["image"])) $row->picwithlogo = $form["image"];
						if(isset($form["firstname"])) $row->firstname = $form["firstname"];
						if(isset($form["lastname"])) $row->lastname = $form["lastname"];
						if(isset($form["middlename"])) $row->middlename = $form["middlename"];
						if(isset($form["occupation"])) $row->occupation = $form["occupation"];
						if(isset($form["aboutme"])) $row->aboutme = $form["aboutme"];
						if(isset($form["sex"])) $row->sex = $form["sex"];
						if(isset($form["username"])) $row->username = $form["username"];
						$this->getServiceLocator()->get("UserComponent")->update($row);
						$result = $row->getJson();
						$result["result_code"]="success";
						$result["success"]="updated";
						//$result["photo"]=$row->pictwithlogo;
					}else{
						$result["result_code"]="not connected";
					}
				}catch(\Exception $e){
					$result["code"]="error";
					$result["error"]=$e->getMessage();
				}
			}else{
				$result["code"]="no form posted";
			}
		}else{
			$result["code"]="not connected";
		}
		return new JsonModel($result);
	}
	public function authAction()
    {
        $this->init();
		$post = $this->request->getPost();
        $email = $this->params()->fromPost('email');
        $rememberMe = $this->getRequest()->getPost('remember_me');
        $password = $this->request->getPost('password');
        $adapter = $this->getAuthService()->getAdapter();
        $adapter->setIdentityValue($email);
        $adapter->setCredentialValue($password);
        
        $authResult = $this->getAuthService()->authenticate();
        
        if ($authResult->isValid()) {
			$user = $this->identity();
			$message = $user->getJson();
			$message['result_code'] = "success";
			$message['success'] = 'Authentication successful';
            return new JsonModel($message);
        }
        $user = $this->userComponent->getByEmailAndPassword($email, $password);
        if($user!=null){
        	$message = $user->getJson();
        	$message['result_code'] = "not_confirm";
        	$message['warning'] = 'Confirm your account';
        	return new JsonModel($message);
        }
        
        $message = array(
            'result_code' => "error",
            'error' => 'Your authentication credentials are not valid'
        );
        return new JsonModel($message);
    }
	
	public function logoutAction()
    {
        $me = $this->getServiceLocator()->get('ReverseOAuth2\Facebook');
        $me->clear();
        $this->getAuthService()->clearIdentity();
        $message = array(
                'success' => 'Logged out',
        ); 
		return new JsonModel($message);
        //$this->flashmessenger()->addMessage("You've been logged out");
        //return $this->redirect()->toRoute('home');
    }

    public function fbloginAction()
    {
        $resultMessage = "";
        $this->init();
        $me = $this->getServiceLocator()->get('ReverseOAuth2\Facebook');        
       
        if (strlen($this->params()->fromQuery('code')) > 10) {
            echo "Here";
            if ($me->getToken($this->request)) {
                $token = $me->getSessionToken(); // token in session
            } else {
                $token = $me->getError(); // last returned error (array)
            }
            
            $adapter = $this->getServiceLocator()->get('ReverseOAuth2\Auth\Adapter'); // added in module.config.php
            $adapter->setOAuth2Client($me); // $me is the oauth2 client
            
            $rs = $this->getAuthService()->authenticate($adapter); // provides an eventManager 'oauth2.success'
            
            if (! $rs->isValid()) {
              
                $message = array(
                    'error' => "Authentication failed: cause " . $rs->getMessages()
                );
                return new JsonModel($message);
            } else {
               
                //return new JsonModel(array('error' => $rs->getIdentity()));
                $result = $this->performFacebooAuth($rs->getIdentity(), (array) $me->getSessionToken());
               
                
                $this->getAuthService()
                    ->getStorage()
                    ->write($result['user']);
                $message = array(
                    'success' => "Facebook authenticate successful 1",
                    'state' => $result['id'],
                    'user' => $result['user']
                );
                if($result['id']!=1 || $result['id']!=2)
                {
                    return $this->redirect()->toRoute('queue');
                }
                return new ViewModel($message);
            }
        } else {
            $url = $me->getUrl();
            $message = array(
                'success' => "Facebook authenticate successful 2 ",
                'url' => $url
            );
            return new JsonModel($message);
        }
       
    }

    public function signinAction()
    {
      
        $email = $this->getRequest()->getPost('email');
        $rememberMe = $this->getRequest()->getPost('remember_me');
        $password = $this->getRequest()->getPost('password');
        $this->init();
        
        //$this->getAuthService()->setStorage($this->getSessionStorage());
        
        $adapter = $this->getAuthService()->getAdapter();
        $adapter->setIdentityValue($email);
        $adapter->setCredentialValue($password);
        
        $authResult = $this->getAuthService()->authenticate();
        
        if ($authResult->isValid()) {
          /*  $this->getAuthService()->getStorage()->write($result['user']);
            if ($rememberMe == 1) {
                $this->getAuthService()
                    ->getStorage()
                    ->setRememberMe(1);
            }*/
            $message = array(
                'success' => 'Authentication successful'
            );
            return new JsonModel($message);
        }
        $message = array(
            'error' => 'Your authentication credentials are not valid'
        );
        return new JsonModel($message);
    }

    /**
     * $token must be cast to array
     * 
     * @param unknown $params            
     * @param unknown $token            
     */
    public function performFacebooAuth($params, $token)
    {
        $returnId = 0;
        $userFacebook = $this->userFacebookComponent->get($params['id']);
        if (! $userFacebook) {
            $userFacebook = new UserFacebook();
            $userFacebook->uid = $params['id'];
            $userFacebook->name = $params['name'];
            $userFacebook->email = $params['email'];
            $userFacebook->firstname = $params['first_name'];
            $userFacebook->lastname = $params['last_name'];
            $userFacebook->username = $params['username'];
            $userFacebook->sex = $params['gender'];
            $userFacebook->locale = $params['locale'];
            $userFacebook->timezone = $params['timezone'];
            $userFacebook->verified = $params['verified'];
            $userFacebook->link = $params['link'];
            $this->userFacebookComponent->insert($userFacebook);
        }
       
        
        $users = $this->userComponent->getByUserFacebookUIDEmail($params['id'], $params['email']);
        $user = $users[0];
        if (! $user) {
            $user = new User();
            $user->firstname = $params['first_name'];
            $user->lastname = $params['last_name'];
            $user->sex = $params['gender'];
            $user->username = $params['username'];
            $user->locale = $params['locale'];
            $user->email = $params['email'];
            $user->token = $token['access_token'];
            $expire = (isset($params['token']['expires'])) ? $params['token']['expires'] : 3600;
            $date = new DateTime('now');
            
            $date->modify('+' . $expire . ' seconds');
            $user->valid_token = $date;
            $user->userFacebook = $userFacebook;
            $this->userComponent->insert($user);
            $returnId = 1;
        } else {
            if (! $user->userFacebook) {
                $user->userFacebook = $userFacebook;
                $this->userComponent->insert($user);
                $returnId = 2;
            }
        }
        return array(
            'id' => $returnId,
            'user' => $user
        );
    }

 
}
